/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.chlitina.store.common.oss;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.LoggerFactory;

import com.chlitina.store.common.config.Global;

/**
 * CKFinderConnectorServlet
 * @author ThinkGem
 * @version 2013-01-15
 */
public class CkeditorUploadServlet extends HttpServlet {
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(CkeditorUploadServlet.class);
	private static final long serialVersionUID = 1L;
	private static String MAX_SIZE = Global.getConfig("web.maxUploadSize");
	private static String OSS_PATH = Global.getConfig("ossPath");
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		fileUpload(request,response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		fileUpload(request,response);
	}
	
	private void fileUpload(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException{	
		String fileUrl = "";
		//设置字符编码为UTF-8，支持汉字显示
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		// CKEditor提交的很重要的一个参数  
        String callback = request.getParameter("CKEditorFuncNum");
		try {			
			// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
			DiskFileItemFactory dfif = new DiskFileItemFactory();
			dfif.setSizeThreshold(1024 * 5);// 设置上传文件时用于临时存放文件的内存大小,这里是5k.多于的部分将临时存在硬盘

			//用以上工厂实例化上传组件
			ServletFileUpload sfu = new ServletFileUpload(dfif);
			//设置最大上传尺寸
			sfu.setSizeMax(Long.parseLong(MAX_SIZE));	
			
			//从request得到 所有 上传域的列表		
			List<FileItem> fileList = sfu.parseRequest(request);
			//没有选择上传文件
			if (fileList == null || fileList.size() == 0) {
				out.println("请选择上传文件");
				return;
			}		
			//得到所有上传的文件
			Iterator fileItr = fileList.iterator();
			//循环处理所有文件
			while (fileItr.hasNext()) {			
				//得到当前文件
				FileItem fileItem = (FileItem) fileItr.next();
				if(!fileItem.isFormField()){
					//得到文件的完整路径
					fileUrl = OSSServer.save(fileItem);
				}			
			}
			// 返回“图像”选项卡并显示图片  
	        out.println("<script type=\"text/javascript\">");    
	        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + OSS_PATH + fileUrl + "','')");    
	        out.println("</script>");  
		} catch (FileUploadException e) {//处理文件尺寸过大异常
			String max = String.valueOf(Long.parseLong(MAX_SIZE)/(1024*1024));
			out.println("<script type=\"text/javascript\">");    
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件大小不得大于" + max +"M！');");   
            out.println("</script>");  
			return;
		} catch (Exception e) {
			out.println("<script type=\"text/javascript\">");    
            out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件上传出错！');");   
            out.println("</script>");  
			return;
		} 							
	}
}
